package com.globallogic.vkulyk.SSHTool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CLIHandler {
	private String[] args = null;
	private String loggerConfigFile = "ssht-logback.xml";
	private Logger logger = null;

	public static void main(String[] args) {
		new CLIHandler().run(args);
		System.exit(0);
	}

	public void run(String[] args) {
		this.args = args;
		setupLogging();
		defineModeAndCallRelevantModeHandler();
	}

	private void setupLogging() {
		setupConfigFile();
		logUncaughtException();
	}

	private void setupConfigFile() {
		if (System.getProperty("logback.configurationFile") == null) {
			System.setProperty("logback.configurationFile", loggerConfigFile);
		}
		logger = LoggerFactory.getLogger(CLIHandler.class);
		logger.debug("Logger config file: {}",
				System.getProperty("logback.configurationFile"));
	}

	private void logUncaughtException() {
		Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
			public void uncaughtException(Thread t, Throwable e) {
				logger.error("Uncaught Exception: ", e);
				System.exit(1);
			};
		});
	}

	private void defineModeAndCallRelevantModeHandler() {
		logger.debug("Defining mode..");
		String argsInOneString = "";
		for (String arg : args) {
			argsInOneString = argsInOneString.concat(" " + arg);
		}
		if (argsInOneString.contains("@")) {
			logger.debug("Mode is 'user data'..");
			new CLIUserDataModeHandler(args).run();
		} else if (argsInOneString.contains(" -t ")) {
			logger.debug("Mode is 'target'..");
			new CLITargetModeHandler(args).run();
		} else {
			logger.error("ERROR: Illegal arguments '{}'. Exiting.",
					argsInOneString);
			System.exit(1);
		}
	}

}
